import axios, { type AxiosRequestConfig } from 'axios';

/** 请求类型 */
export const enum RequestMethod {
    POST = 'POST',
    GET = 'GET',
}

/** 请求结果 */
export interface IResult<T = any> {
    code: number;
    data: T;
    err: string;
    msg: any;
    success: boolean;
    timestamp: number;
}

/**
 * 创建Request实例
 * @param config 实例配置
 * @returns 实例
 */
export function createRequestInstance(config: { baseUrl?: string; timeout?: number }) {
    const instance = axios.create({
        baseURL: config.baseUrl,
        timeout: config.timeout,
        headers: {
            'Content-Type': 'application/json',
        },
    });

    // 响应 拦截器
    instance.interceptors.response.use(
        (res) => {
            return res.data;
        },
        (err) => {
            return Promise.resolve(err);
        },
    );

    return instance;
}

/** 基础请求实例 */
export const baseInstance = createRequestInstance({
    baseUrl: import.meta.env.HG_API_BASE_URL,
    timeout: 30000,
});

/** 基础请求 */
export function baseRequest<T = any, D = any>(config: AxiosRequestConfig<D>) {
    return baseInstance.request<any, IResult<T>, D>(config);
}
